<template>
  <div class="situation-container layout-container">
    <HeaderComponent title="态势对象数据" :loading="state.loading">
      <template #actions>
        <a-space>
          <a-button @click="handleExport">
            <template #icon><ExportOutlined /></template>
            导出
          </a-button>
          <a-button @click="state.showImportModal = true">
            <template #icon><ImportOutlined /></template>
            导入
          </a-button>
          <a-button @click="handleDataSync">
            <template #icon><SyncOutlined /></template>
            数据同步
          </a-button>
          <a-button type="primary" @click="handleCreate">
            <template #icon><PlusOutlined /></template>
            新建态势对象
          </a-button>
          <a-button @click="handleRelationshipManage">
            <template #icon><ApartmentOutlined /></template>
            关系维护
          </a-button>
          <a-button type="primary" @click="handleExportToGraph">
            <template #icon><DeploymentUnitOutlined /></template>
            导入知识图谱
          </a-button>
        </a-space>
      </template>
    </HeaderComponent>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <a-space wrap>
        <a-select
          v-model:value="filters.object_type"
          placeholder="对象类型"
          style="width: 150px"
          allowClear
          @change="handleObjectTypeChange"
        >
          <a-select-option v-for="type in objectTypes" :key="type.value" :value="type.value">
            {{ type.label }}
          </a-select-option>
        </a-select>

        <a-select
          v-model:value="filters.equipment_category"
          placeholder="装备类别"
          style="width: 150px"
          allowClear
          @change="handleFilterChange"
          :disabled="!filters.object_type"
        >
          <a-select-option v-for="category in equipmentCategories" :key="category.value || category" :value="category.value || category">
            {{ getEquipmentCategoryLabel(category.value || category) }}
          </a-select-option>
        </a-select>

        <a-select
          v-model:value="filters.deployment_status"
          placeholder="部署状态"
          style="width: 150px"
          allowClear
          @change="handleFilterChange"
        >
          <a-select-option v-for="status in deploymentStatuses" :key="status.value" :value="status.value">
            {{ status.label }}
          </a-select-option>
        </a-select>

        <a-input
          v-model:value="filters.organization"
          placeholder="所属单位"
          style="width: 180px"
          allowClear
        />

        <a-input-search
          v-model:value="filters.search"
          placeholder="搜索名称或编码"
          style="width: 250px"
          allowClear
          @search="handleSearch"
        />

        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-button @click="resetFilters">重置</a-button>
      </a-space>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section" v-if="statistics">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card>
            <a-statistic title="总数" :value="statistics.total_count" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic title="已部署" :value="statistics.by_status['已部署'] || 0" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic title="待部署" :value="statistics.by_status['待部署'] || 0" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic title="维护中" :value="statistics.by_status['维护中'] || 0" />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :dataSource="dataList"
        :columns="columns"
        :pagination="pagination"
        :loading="state.loading"
        :scroll="{ x: 1100, y: 'calc(100vh - 400px)' }"
        :size="'middle'"
        @change="handleTableChange"
        rowKey="id"
        :bordered="true"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'object_type'">
            <a-tag :color="getTypeColor(record.object_type)">
              {{ getTypeLabel(record.object_type) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'equipment_category'">
            <a-tag color="blue" v-if="record.equipment_category">
              {{ getEquipmentCategoryLabel(record.equipment_category) }}
            </a-tag>
            <span v-else>-</span>
          </template>

          <template v-else-if="column.key === 'deployment_status'">
            <a-tag :color="getStatusColor(record.deployment_status)">
              {{ record.deployment_status || '未知' }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'description'">
            <a-tooltip :title="record.description" v-if="record.description">
              {{ record.description }}
            </a-tooltip>
            <span v-else>-</span>
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button size="small" @click="handleView(record)">查看</a-button>
              <a-button size="small" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm
                title="确认删除该对象吗？"
                ok-text="确认"
                cancel-text="取消"
                @confirm="handleDelete(record.id)"
              >
                <a-button size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新建/编辑弹窗 -->
    <SituationFormModal
      v-model:open="state.showFormModal"
      :edit-data="state.currentObject"
      :object-types="objectTypes"
      :deployment-statuses="deploymentStatuses"
      @success="handleFormSuccess"
    />

    <!-- 详情弹窗 -->
    <SituationDetailModal
      v-model:open="state.showDetailModal"
      :object-data="state.currentObject"
      :object-types="objectTypes"
    />

    <!-- 导入弹窗 -->
    <SituationImportModal
      v-model:open="state.showImportModal"
      @success="handleImportSuccess"
    />

    <!-- 关系维护弹窗 -->
    <SituationRelationshipModal
      v-model:open="state.showRelationshipModal"
    />

    <!-- 知识图谱导出弹窗 -->
    <SituationGraphExportModal
      v-model:open="state.showGraphExportModal"
      @success="handleGraphExportSuccess"
    />
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ExportOutlined,
  ImportOutlined,
  PlusOutlined,
  ApartmentOutlined,
  DeploymentUnitOutlined,
  SyncOutlined
} from '@ant-design/icons-vue'
import {
  getSituationObjects,
  deleteSituationObject,
  getSituationTypes,
  getDeploymentStatuses,
  getSituationStatistics,
  exportSituationData,
  getEquipmentCategories,
  getEquipmentCategoryLabels
} from '@/apis'
import HeaderComponent from '@/components/HeaderComponent.vue'
import SituationFormModal from '@/components/SituationFormModal.vue'
import SituationDetailModal from '@/components/SituationDetailModal.vue'
import SituationImportModal from '@/components/SituationImportModal.vue'
import SituationRelationshipModal from '@/components/SituationRelationshipModal.vue'
import SituationGraphExportModal from '@/components/SituationGraphExportModal.vue'

const router = useRouter()

const state = reactive({
  loading: false,
  showFormModal: false,
  showDetailModal: false,
  showImportModal: false,
  showRelationshipModal: false,
  showGraphExportModal: false,
  currentObject: null
})

const filters = reactive({
  object_type: undefined,
  equipment_category: undefined,
  deployment_status: undefined,
  organization: '',
  search: ''
})

const dataList = ref([])
const objectTypes = ref([])
const deploymentStatuses = ref([])
const equipmentCategories = ref([])
const statistics = ref(null)

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条`
})

// 装备类别标签映射（从后端获取）
const equipmentCategoryLabels = ref({})

// 获取装备类别中文标签
function getEquipmentCategoryLabel(value) {
  return equipmentCategoryLabels.value[value] || value
}

const columns = [
  { title: '对象类型', dataIndex: 'object_type', key: 'object_type', width: 120, fixed: 'left' },
  { title: '装备类别', dataIndex: 'equipment_category', key: 'equipment_category', width: 120 },
  { title: '名称', dataIndex: 'name', key: 'name', width: 220, ellipsis: true },
  { title: '编码', dataIndex: 'code', key: 'code', width: 140 },
  { title: '描述', dataIndex: 'description', key: 'description', width: 200, ellipsis: true },
  { title: '所属单位', dataIndex: 'organization', key: 'organization', width: 180, ellipsis: true },
  { title: '部署状态', dataIndex: 'deployment_status', key: 'deployment_status', width: 100 },
  { title: '操作', key: 'action', width: 200, fixed: 'right' }
]

// 获取数据
async function fetchData() {
  state.loading = true
  try {
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize
    }

    // 添加筛选参数
    if (filters.object_type) params.object_type = filters.object_type
    if (filters.equipment_category) params.equipment_category = filters.equipment_category
    if (filters.deployment_status) params.deployment_status = filters.deployment_status
    if (filters.organization) params.organization = filters.organization
    if (filters.search) params.search = filters.search

    const response = await getSituationObjects(params)
    dataList.value = response.items
    pagination.total = response.total
  } catch (error) {
    message.error('获取数据失败: ' + error.message)
  } finally {
    state.loading = false
  }
}

// 获取统计信息
async function fetchStatistics() {
  try {
    const response = await getSituationStatistics()
    statistics.value = response
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 初始化
onMounted(async () => {
  try {
    // 加载类型和状态列表
    const [typesRes, statusesRes, labelsRes] = await Promise.all([
      getSituationTypes(),
      getDeploymentStatuses(),
      getEquipmentCategoryLabels()
    ])
    objectTypes.value = typesRes.types
    deploymentStatuses.value = statusesRes.statuses
    equipmentCategoryLabels.value = labelsRes

    // 加载数据和统计
    await Promise.all([fetchData(), fetchStatistics()])
  } catch (error) {
    message.error('初始化失败: ' + error.message)
  }
})

// 处理表格变化
function handleTableChange(pag) {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData()
}

// 筛选条件变化
function handleFilterChange() {
  pagination.current = 1
  fetchData()
}

// 处理对象类型变化
async function handleObjectTypeChange() {
  // 重置装备类别筛选
  filters.equipment_category = undefined
  equipmentCategories.value = []

  // 如果选择了对象类型，加载对应的装备类别
  if (filters.object_type) {
    try {
      const response = await getEquipmentCategories(filters.object_type)
      // 找到对应类型的装备类别
      const typeCategories = response.find(item => item.object_type === filters.object_type)
      if (typeCategories) {
        equipmentCategories.value = typeCategories.categories
      }
    } catch (error) {
      message.error('获取装备类别失败: ' + error.message)
    }
  }

  handleFilterChange()
}

// 搜索
function handleSearch() {
  pagination.current = 1
  fetchData()
}

// 新建
function handleCreate() {
  state.currentObject = null
  state.showFormModal = true
}

// 查看
function handleView(record) {
  state.currentObject = record
  state.showDetailModal = true
}

// 编辑
function handleEdit(record) {
  state.currentObject = { ...record }
  state.showFormModal = true
}

// 删除
async function handleDelete(id) {
  try {
    await deleteSituationObject(id)
    message.success('删除成功')
    fetchData()
    fetchStatistics()
  } catch (error) {
    message.error('删除失败: ' + error.message)
  }
}

// 表单提交成功
function handleFormSuccess() {
  state.showFormModal = false
  fetchData()
  fetchStatistics()
}

// 导入成功
function handleImportSuccess() {
  state.showImportModal = false
  fetchData()
  fetchStatistics()
}

// 关系维护
function handleRelationshipManage() {
  state.showRelationshipModal = true
}

// 导出到知识图谱
function handleExportToGraph() {
  state.showGraphExportModal = true
}

// 数据同步
function handleDataSync() {
  router.push('/situation/sync-data')
}

// 知识图谱导出成功
function handleGraphExportSuccess() {
  message.success('知识图谱导出成功')
}

// 重置筛选
function resetFilters() {
  filters.object_type = undefined
  filters.equipment_category = undefined
  filters.deployment_status = undefined
  filters.organization = ''
  filters.search = ''
  equipmentCategories.value = []
  pagination.current = 1
  fetchData()
}

// 导出
async function handleExport() {
  try {
    message.loading({ content: '正在导出...', key: 'export' })
    const response = await exportSituationData('json', filters.object_type)

    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/json' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `situation_objects_${new Date().getTime()}.json`
    link.click()
    window.URL.revokeObjectURL(url)

    message.success({ content: '导出成功', key: 'export' })
  } catch (error) {
    message.error({ content: '导出失败: ' + error.message, key: 'export' })
  }
}

// 获取类型标签
function getTypeLabel(type) {
  const found = objectTypes.value.find(t => t.value === type)
  return found ? found.label : type
}

// 获取类型颜色
function getTypeColor(type) {
  const found = objectTypes.value.find(t => t.value === type)
  return found ? found.color : '#666'
}

// 获取状态颜色
function getStatusColor(status) {
  const colorMap = {
    '已部署': 'green',
    '待部署': 'orange',
    '维护中': 'blue',
    '退役': 'gray'
  }
  return colorMap[status] || 'default'
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.situation-container {
  padding: 0;
  background: var(--bg-main);
  min-height: 100vh;
}

.filter-section {
  margin: 16px 24px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.stats-section {
  margin: 0 24px 16px;
}

.table-section {
  margin: 0 24px 24px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

:deep(.ant-statistic-title) {
  font-size: 14px;
  color: #666;
}

:deep(.ant-statistic-content) {
  font-size: 24px;
  font-weight: 600;
}

:deep(.ant-table) {
  font-size: 14px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

:deep(.ant-btn-sm) {
  font-size: 12px;
}

@media (max-width: 1200px) {
  .filter-section {
    margin: 16px;
  }

  .stats-section {
    margin: 0 16px 16px;
  }

  .table-section {
    margin: 0 16px 24px;
  }
}
</style>
